const express = require('express');
const path = require('path')
const bodyParser = require('body-parser'); //第三方模块获取post参数
const session = require('express-session')
const dateformat = require('dateformat'); //处理日期格式
const template = require('art-template'); //第三方模块模板引擎
const morgan = require('morgan') //第三方模块在控制台打印信息
const config = require('config')
const app = express();
//开启静态资源访问
app.use(express.static(path.join(__dirname, 'public')));
//配置bodyparse
app.use(bodyParser.urlencoded({ extended: false }))
    //配置格式化日期方法
template.defaults.imports.dateformat = dateformat;
//判断是开发环境还是生产环境
if (process.env.NODE_ENV == 'development') {
    console.log('当前是开发环境')
        // app.use(morgan('dev')) //在控制台打印信息
} else {
    console.log('当前是生产环境')
}
console.log(config.get('title'))
    //配置session
app.use(session({

    resave: false,
    saveUninitialized: true, //解决命令行提示问题
    secret: 'secret key'
}))
require('./model/connect')
app.use('/admin', require('./middleWare/loginGuard'))
    //引入路由模块
const admin = require('./route/admin')
const home = require('./route/home')
    //为路由匹配路径
app.use('/admin', admin)
app.use('/home', home)

//错误处理中间件
app.use((err, req, res, next) => {
        const result = JSON.parse(err);
        let params = [];
        for (attr in result) {
            if (attr != path) {
                params.push(attr + '=' + result[attr])
            }
        }
        res.redirect(`${result.path}?${params.join('&')}`)
    })
    //配置模板
app.engine('art', require('express-art-template'));
//配置模板路径
app.set('views', path.join(__dirname, 'views'))
    //配置模板后缀
app.set('view engine', 'art')
app.listen(8080);
console.log('服务器创建成功,启动在localhost:8080端口')